package com.fan.shop.dao;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Named;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.fan.shop.domain.Stock;
import com.fan.shop.domain.StockId;

@Named("stockDao")
public class StockDaoImpl implements StockDao {

	private SessionFactory sessionFactory;

	/**
	 * Get Hibernate Session Factory
	 * 
	 * @return SessionFactory - Hibernate Session Factory
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * Set Hibernate Session Factory
	 * 
	 * @param SessionFactory
	 *            - Hibernate Session Factory
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Stock getStock(String itemCode, String storeCode) {
		StockId stockId = new StockId();
		stockId.setItemCode(itemCode);
		stockId.setStoreCode(storeCode);
		Stock stock = (Stock) sessionFactory.getCurrentSession().get(
				Stock.class, stockId);
		return stock;
	}

	@SuppressWarnings("unchecked")
	public List<Stock> getAllStocks() {
		List<Stock> stocks = (List<Stock>) sessionFactory.getCurrentSession()
				.createCriteria(Stock.class).list();
		return stocks;
	}

	public int getSize() {
		return getAllStocks().size();
	}

	public void addStock(Stock stock) {
		sessionFactory.getCurrentSession().save(stock);
	}

	public void updateStock(Stock stock) {
		sessionFactory.getCurrentSession().update(stock);
	}

	public void deleteStock(Stock stock) {
		sessionFactory.getCurrentSession().delete(stock);
	}

	public boolean hasStock(String itemCode, String storeCode) {
		if (getStock(itemCode, storeCode) == null) {
			return false;
		} else {
			return true;
		}
	}

	public List<String> getColumnNames() {

		List<String> columns = new ArrayList<String>();
		columns.add("Item Code");
		columns.add("Icon");
		columns.add("Store Code");
		columns.add("Quantity");
		columns.add("Hold Quantity");
		columns.add("Net Price");
		columns.add("Cost");
		
		return columns;
	}

	@SuppressWarnings("unchecked")
	public List<Stock> getStocksByStore(String storeCode) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(Stock.class);
		criteria.add(Restrictions.eq("id.storeCode", storeCode));
		List<Stock> list = (List<Stock>)criteria.list();
		return list;
	}

}
